package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.dto.ApiResponse;
import org.example.entity.Order;
import org.example.entity.OrderItem;
import org.example.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 订单控制器
 * 演示Sharding-JDBC的分片功能
 */
@Slf4j
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public ApiResponse<String> createOrder(@RequestParam Long userId) {
        try {
            // 创建订单
            Order order = new Order();
            order.setUserId(userId);
            order.setOrderNo("ORDER_" + System.currentTimeMillis());
            order.setTotalAmount(new BigDecimal("199.99"));
            order.setOrderStatus("CREATED");
            order.setRemark("测试订单 - Sharding-JDBC分片");

            // 创建订单项
            List<OrderItem> orderItems = new ArrayList<>();
            
            OrderItem item1 = new OrderItem();
            item1.setProductId(1001L);
            item1.setProductName("iPhone 15 Pro");
            item1.setPrice(new BigDecimal("99.99"));
            item1.setQuantity(1);
            item1.setAmount(new BigDecimal("99.99"));
            
            OrderItem item2 = new OrderItem();
            item2.setProductId(1002L);
            item2.setProductName("MacBook Pro");
            item2.setPrice(new BigDecimal("100.00"));
            item2.setQuantity(1);
            item2.setAmount(new BigDecimal("100.00"));
            
            orderItems.add(item1);
            orderItems.add(item2);

            // 保存订单
            boolean success = orderService.createOrder(order, orderItems);
            
            if (success) {
                return ApiResponse.success("订单创建成功，订单ID: " + order.getOrderId());
            } else {
                return ApiResponse.error("订单创建失败");
            }
        } catch (Exception e) {
            log.error("创建订单异常", e);
            return ApiResponse.error("创建订单异常: " + e.getMessage());
        }
    }

    /**
     * 根据用户ID查询订单
     */
    @GetMapping("/user/{userId}")
    public ApiResponse<List<Order>> getOrdersByUserId(@PathVariable Long userId) {
        try {
            List<Order> orders = orderService.getOrdersByUserId(userId);
            return ApiResponse.success(orders);
        } catch (Exception e) {
            log.error("查询用户订单异常", e);
            return ApiResponse.error("查询用户订单异常: " + e.getMessage());
        }
    }

    /**
     * 根据订单状态查询订单
     */
    @GetMapping("/status/{orderStatus}")
    public ApiResponse<List<Order>> getOrdersByStatus(@PathVariable String orderStatus) {
        try {
            List<Order> orders = orderService.getOrdersByStatus(orderStatus);
            return ApiResponse.success(orders);
        } catch (Exception e) {
            log.error("查询订单状态异常", e);
            return ApiResponse.error("查询订单状态异常: " + e.getMessage());
        }
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{orderId}")
    public ApiResponse<Order> getOrderDetail(@PathVariable Long orderId) {
        try {
            Order order = orderService.getOrderDetail(orderId);
            if (order != null) {
                return ApiResponse.success(order);
            } else {
                return ApiResponse.error("订单不存在");
            }
        } catch (Exception e) {
            log.error("查询订单详情异常", e);
            return ApiResponse.error("查询订单详情异常: " + e.getMessage());
        }
    }

    /**
     * 更新订单状态
     */
    @PutMapping("/{orderId}/status")
    public ApiResponse<String> updateOrderStatus(@PathVariable Long orderId, 
                                                @RequestParam String orderStatus) {
        try {
            boolean success = orderService.updateOrderStatus(orderId, orderStatus);
            if (success) {
                return ApiResponse.success("订单状态更新成功");
            } else {
                return ApiResponse.error("订单状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新订单状态异常", e);
            return ApiResponse.error("更新订单状态异常: " + e.getMessage());
        }
    }

    /**
     * 批量创建订单（用于测试分片效果）
     */
    @PostMapping("/batch")
    public ApiResponse<String> createBatchOrders(@RequestParam(defaultValue = "10") int count) {
        try {
            int successCount = 0;
            for (int i = 0; i < count; i++) {
                // 模拟不同的用户ID（0-9）
                Long userId = (long) (i % 10);
                
                Order order = new Order();
                order.setUserId(userId);
                order.setOrderNo("BATCH_ORDER_" + System.currentTimeMillis() + "_" + i);
                order.setTotalAmount(new BigDecimal("99.99"));
                order.setOrderStatus("CREATED");
                order.setRemark("批量测试订单 " + i);

                List<OrderItem> orderItems = new ArrayList<>();
                OrderItem item = new OrderItem();
                item.setProductId(1000L + i);
                item.setProductName("测试商品 " + i);
                item.setPrice(new BigDecimal("99.99"));
                item.setQuantity(1);
                item.setAmount(new BigDecimal("99.99"));
                orderItems.add(item);

                boolean success = orderService.createOrder(order, orderItems);
                if (success) {
                    successCount++;
                }
            }
            
            return ApiResponse.success("批量创建订单完成，成功: " + successCount + " / " + count);
        } catch (Exception e) {
            log.error("批量创建订单异常", e);
            return ApiResponse.error("批量创建订单异常: " + e.getMessage());
        }
    }
} 